import { useState } from "react";

/**
 * 通用的 useReducer 函数
 * @param {function} reducer reducer函数，标准格式
 * @param {any} initialState 初始状态
 * @param {function} fn 计算初始值的函数
 * @returns 
 */
export default function useReducer(reducer, initialState, fn) {
    const [state, setState] = useState(fn ? fn(initialState) : initialState)

    function dispatch(action) {
        const newState = reducer(state, action)
        console.log(`日志: n的状态 ${state} -> ${newState}`);
        setState(newState)
    }

    return [state, dispatch]
}